package xyz.xtt.pay.service.impl;

import java.util.List;
import java.util.Objects;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import xyz.xtt.exchange.dto.MintPriceConfigItem;
import xyz.xtt.pay.constants.ErrorMessage;
import xyz.xtt.pay.exception.ChainException;
import xyz.xtt.pay.service.IConfigService;

@RefreshScope
@Service
public class ConfigServiceImpl implements IConfigService {
	/**
	 * 私人铸造价格配置
	 */
	@Value("${asset.mint.PriceConfig}")
	private String personalMintPriceConfig;

	@Override
	public String calculatePersonalMintPrice(Integer mintNum) {
		List<MintPriceConfigItem> config = getPersonalMintPriceConfig();
		if (CollectionUtil.isEmpty(config)) {
			throw new ChainException(ErrorMessage.MINT_PRICE_CONFIG_INVALID);
		}
		MintPriceConfigItem mintPriceConfigItem = config.stream().filter(x -> x.getMax() >= mintNum && x.getMin() <= mintNum).findFirst().orElse(null);
		if (Objects.isNull(mintPriceConfigItem)) {
			throw new ChainException(ErrorMessage.MINT_PRICE_CONFIG_INVALID);
		}
		return mintPriceConfigItem.getPrice().toPlainString();
	}

	public List<MintPriceConfigItem> getPersonalMintPriceConfig() {
		final String config = personalMintPriceConfig;
		if (JSONUtil.isTypeJSON(config)) {
			return JSONUtil.toList(JSONUtil.parseArray(config), MintPriceConfigItem.class);
		} else {
			return null;
		}
	}
}
